package net.sf.cldsql.dj.utl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * JsonUtl
 */
public class JsonUtl {

    private Object value;
    private String quotation;

    public JsonUtl (String quotation) {
        this.quotation = quotation;
    }
    
    public JsonUtl () {
        this("\"");
    }
    
    /**
     * @param params
     * @return
     */
    public JsonUtl setValue(Object value) {
        this.value = value;
        return this;
    }
    
    public JsonUtl buildJson(StringBuilder json, Object object) {

        if (object == null) {
            json.append("null");
        } else if (object instanceof CharSequence) {
            json.append(quotation + object.toString() + quotation);
        } else if (object instanceof Short
                || object instanceof Integer
                || object instanceof Long
                || object instanceof BigDecimal) {
            json.append(object.toString());
        } else if (object instanceof Map) {
            json.append('{');
            boolean needComma = false;
            Map map = (Map)object;
            for (Object key : map.keySet()) {
                if (needComma) {
                    json.append(", ");
                }
                
                json.append(quotation);
                json.append(key);
                json.append(quotation);
                json.append(":");
                buildJson(json, map.get(key));
                
                needComma |= true;
            }
            json.append('}');
        } else if (object instanceof List) {
            json.append('[');
            boolean needComma = false;
            for (Object item : (List)object) {
                if (needComma) {
                    json.append(", ");
                }
                
                buildJson(json, item);
                
                needComma |= true;
            }
            json.append(']');
        } else {
            json.append(quotation + object.toString() + quotation);
        }
        
        return this;
    }
    
    public String toString() {
        StringBuilder json = new StringBuilder();
        buildJson(json, value);
        return json.toString();
    }

    /**
     * @return value
     */
    public Object getValue() {
        return value;
    }

}
